package com.csliubo.eclipse.plugin.sqlgenerator.popup.actions;

import java.io.File;
import java.text.MessageFormat;

import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.csliubo.eclipse.plugin.sqlgenerator.core.DataGenerator;

public class GenerateAction implements IObjectActionDelegate {

	private Shell shell;
	private ISelection selection;
	private static final String MSG_FORMAT = "\t at {0}.{1}({2}:{3})\n";

	/**
	 * Constructor for Action1.
	 */
	public GenerateAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		if (!(selection instanceof IStructuredSelection)) {
			return;
		}
		String msg = "数据搞定拉:)";
		try {
			DataGenerator.generate(getFileFromSelection(selection));
		} catch (Throwable e) {
			StackTraceElement[] elements = e.getStackTrace();
			msg = e.toString()+"\n"+buildErrorMsg(elements);
		}
		MessageDialog.openInformation(shell, "SqlGenerator", msg);
	}

	private String buildErrorMsg(StackTraceElement[] elements) {
		StringBuilder sb = new StringBuilder();
		for (StackTraceElement element : elements) {
			sb.append(MessageFormat.format(MSG_FORMAT, element.getClassName(),
					element.getMethodName(), element.getFileName(),
					element.getLineNumber()));
		}
		return sb.toString();
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

	private File getFileFromSelection(ISelection selection) {
		StructuredSelection sel = (StructuredSelection) selection;
		if (sel.size() != 1) {
			throw new RuntimeException("selection size is 0 pls.check");
		}
		Object object = sel.getFirstElement();
		IResource resource = null;
		if (object instanceof IResource) {
			resource = (IResource) object;
			return resource.getLocation().toFile();
		}
		return null;
	}

}
